﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;
using WorkFlowCore.Authorization;
using WorkFlowCore.Framework.MultipleApp;
using WorkFlowCore.IRepositories;
using WorkFlowCore.Workflows;
using WorkFlowCore.WorkTasks;

namespace WorkFlowCore.Framework.Repositories4EF
{
    public class WorkflowRepository : BasicRepository<Workflow, Guid>, IWorkflowRepository
    {
        private readonly IWorkflowSession session;

        public WorkflowRepository(IWorkflowSession session,IDbContextProvider<WorkflowDbContext> dbContextProvider) : base(session,dbContextProvider)
        {
            this.session = session;
        }

        public async Task<List<string>> GetAllExistsAppIds()
        {
            return await (await GetDbContextAsync()).Set<WorkflowVersionInfo>().Select(w=>w.AppId).Distinct().ToListAsync();
        }

        public async Task<List<Workflow>> GetAllWorkflowsWithVersion()
        {
            var result = new List<Workflow>();
            var workflows = await (await GetDbContextAsync()).Set<Workflow>().WhereMultipleApp(session?.User?.AppId).Where(w => !w.Deleted).ToListAsync();
            var workflowIds = workflows.Select(w => w.Id);
            var allVersions = await (await GetDbContextAsync()).Set<WorkflowVersionInfo>().WhereMultipleApp(session?.User?.AppId).Where(v => workflowIds.Contains(v.WorkflowId)).Select(v =>new {v.WorkflowId,v.VersionNo}).ToListAsync();


            workflows.ForEach(w =>
            {
                var versions = allVersions.Where(v => v.WorkflowId == w.Id);
                result.AddRange(versions.Select(v => new Workflow
                {
                    Id = w.Id,
                    WorkflowNo = w.WorkflowNo,
                    Name = w.Name,
                    ActiveVersion = v.VersionNo
                }));
            });
            return result.OrderBy(w=>w.Name).ToList();
        }

        public async Task<Dictionary<Guid, int>> GetWorkflowVersionCount(Guid[] workflowIds)
        {
            workflowIds = (workflowIds ?? Array.Empty<Guid>()).Distinct().ToArray();
            if (workflowIds.Length == 0)
            {
                return new Dictionary<Guid, int>();
            }

            var allVersions = await(await GetDbContextAsync()).Set<WorkflowVersionInfo>().WhereMultipleApp(session?.User?.AppId)
                .Where(v => workflowIds.Contains(v.WorkflowId))
                .GroupBy(v => v.WorkflowId)
                .Select(v => new { v.Key, Count = v.Count() })
                .ToListAsync();
            return allVersions.ToDictionary(v => v.Key, v => v.Count);
        }
    }
}
